package com.shop.cereshop.app.service.faceCheck.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.shop.cereshop.app.service.faceCheck.FaceCheckService;
import com.shop.cereshop.app.utils.HttpUtils;
import com.shop.cereshop.commons.domain.user.faceCheck.FaceCheckModel;
import com.shop.cereshop.commons.domain.user.faceCheck.respond.AliFaceCheckRespond;
import com.shop.cereshop.commons.domain.user.faceCheck.respond.FaceCheckRespond;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 阿里人脸检测实现类
 */
@Service("alifacecheckserviceimpl")
public class AliFaceCheckServiceImpl implements FaceCheckService {
    @Value("${ali.facecheck.appcode}")
    String appcode;
    @Value("${ali.facecheck.host}")
    String host;
    @Value("${ali.facecheck.path}")
    String path;

    public static void main(String[] args) {
        AliFaceCheckServiceImpl aliFaceCheckService = new AliFaceCheckServiceImpl();
        FaceCheckModel model = new FaceCheckModel();
        model.setName("付晓敏");
        model.setIdCardNumber("110101199001011234");
        model.setImageUrl("https://img.alicdn.com/imgextra/i1/O1CN01qZjXjv1Q5Xw1Xw1Xw_!!6000000002785-0-tps-500-500.jpg");
        FaceCheckRespond faceCheckRespond = aliFaceCheckService.faceCheck( model);
    }
    @Override
    public FaceCheckRespond faceCheck(FaceCheckModel model) {
        String method = "POST";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<String, String>();
        bodys.put("name", model.getName());
        bodys.put("id", model.getIdCardNumber());

       /* bodys.put("image_url", "确认可下载的服务器图片地址（image_url与image二选一）");
        bodys.put("image", "人脸图片的base64编码（image_url与image二选一）;*/
        if (StrUtil.isNotEmpty(model.getImageUrl())) {
            bodys.put("image_url", model.getImageUrl());
        } else if (StrUtil.isNotEmpty(model.getImageBase64())) {
            bodys.put("image", model.getImageBase64().replaceAll("data:image/jpeg;base64,", ""));
        } else {
            return FaceCheckRespond.builder().success(false).build();
        }
        //image_url与image是两种人脸图片传参的方式，选一个即可，删掉另一个入参。
        //使用base64字符串传参，如果报参数image_format错误，请对base64字符串做URLencode处理
        try {
            /**
             * 重要提示如下:
             * HttpUtils请从\r\n\t    \t* https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java\r\n\t    \t* 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            System.out.println((response.getStatusLine().getStatusCode()));
            if (response.getStatusLine().getStatusCode() == 200) {
                //判断response.getEntity() 是否成功
                if (response.getEntity() != null) {
                    String entity = EntityUtils.toString(response.getEntity());
                    AliFaceCheckRespond bean = JSONUtil.toBean(entity, AliFaceCheckRespond.class);
                    if (bean.getStatus().equals("OK")) {
                        return FaceCheckRespond.builder().success(true)
                                .reqParam(JSONUtil.toJsonStr(bodys))
                                .name(model.getName())
                                .idCardNumber(model.getIdCardNumber())
                                .reqResp(entity)
                                .build();
                    } else {
                        return FaceCheckRespond.builder()
                                .success(false)
                                .reqParam(JSONUtil.toJsonStr(bodys))
                                .name(model.getName())
                                .idCardNumber(model.getIdCardNumber())
                                .reqResp(entity)
                                .build();
                    }
                }
            }
        } catch (Exception e) {
            return FaceCheckRespond.builder().success(false).build();
        }
        return FaceCheckRespond.builder().success(false).build();
    }
}
